package com.lswms.service.impl;

import com.lswms.common.exception.ErrorCode;
import com.lswms.common.exception.RenException;
import com.lswms.common.service.impl.CrudServiceImpl;
import com.lswms.common.utils.MoneyUtil;
import com.lswms.common.utils.ZqDateUtil;
import com.lswms.dao.YnLotteryDao;
import com.lswms.dto.YnLotteryDTO;
import com.lswms.dto.YnLotteryRecordDTO;
import com.lswms.dto.vo.resp.LotteryInfoResp;
import com.lswms.entity.YnLotteryEntity;
import com.lswms.entity.YnLotteryRecordEntity;
import com.lswms.entity.YnSignRecordEntity;
import com.lswms.entity.YnUserEntity;
import com.lswms.service.YnLotteryRecordService;
import com.lswms.service.YnLotteryService;
import com.lswms.service.YnSignRecordService;

import java.math.BigDecimal;
import java.util.Calendar;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import lombok.extern.slf4j.Slf4j;

import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;

/**
 * 抽奖表
 *
 * @author Mark sunlightcs@gmail.com
 * @since 1.0.0 2020-05-06
 */
@Service
@Slf4j
public class YnLotteryServiceImpl extends CrudServiceImpl<YnLotteryDao, YnLotteryEntity, YnLotteryDTO> implements YnLotteryService {

	@Autowired
	private YnLotteryRecordService ynLotteryRecordService;
	
	@Autowired
	private YnSignRecordService ynSignRecordService;

	
    @Override
    public QueryWrapper<YnLotteryEntity> getWrapper(Map<String, Object> params){
    	Long id = (Long)params.get("id");
    	String signNo = (String)params.get("signNo");

        QueryWrapper<YnLotteryEntity> wrapper = new QueryWrapper<>();
        wrapper.eq(id != null, "id", id);
        wrapper.eq(StringUtils.isNotBlank(signNo), "sign_no", signNo);

        return wrapper;
    }

    /**
     * 添加抽奖信息
     */
	@Override
	public void createLottery(YnLotteryEntity entity) {
		log.info("添加抽奖信息:{}",JSON.toJSONString(entity));
		String yyyyMMdd = ZqDateUtil.yyyyMMdd(ZqDateUtil.getNow());
		//查询期数
		QueryWrapper<YnLotteryEntity> wrapper = new QueryWrapper<YnLotteryEntity>();
		wrapper.eq(StringUtils.isNotBlank(yyyyMMdd), "sign_no", yyyyMMdd);
		YnLotteryEntity lottery = baseDao.selectOne(wrapper);
		if(lottery == null){
			baseDao.insert(entity);
		}
	}

	/**
	 * 抽奖信息
	 */
	@Override
	public LotteryInfoResp lotteryInfo(YnUserEntity ynuser) {
		String yyyyMMdd = ZqDateUtil.yyyyMMdd(ZqDateUtil.getNow());
		log.info("抽奖信息:{}",yyyyMMdd);
    	//开奖时间（第二天）
    	String signTime = ZqDateUtil.yyyy_MM_dd(ZqDateUtil.addDate(ZqDateUtil.getNow(), 1, Calendar.DAY_OF_MONTH));
		//查询期数
		QueryWrapper<YnLotteryEntity> wrapper = new QueryWrapper<YnLotteryEntity>();
		wrapper.eq(StringUtils.isNotBlank(yyyyMMdd), "sign_no", yyyyMMdd);
		YnLotteryEntity lottery = baseDao.selectOne(wrapper);
		//返回
		LotteryInfoResp resp = new LotteryInfoResp();
		if(lottery != null){
			resp.setId(lottery.getId());
			resp.setSignNo(lottery.getSignNo());
			resp.setNoDesc(lottery.getNoDesc());
			resp.setOpenTime(signTime+" 10:00:00");
			resp.setLotteryAmount(MoneyUtil.bigDecimal2String(lottery.getLotteryAmount(), 2));
			//显示人数=实际人数+机器人数
			resp.setLotteryCount(lottery.getLotteryCount() + lottery.getLotteryCountj());
			resp.setLotteryTime(lottery.getLotteryTime());
			
			String time = lottery.getLotteryTime();
			String startTime = time.split("#")[0];
			String endTime = time.split("#")[1];
			Date now = ZqDateUtil.getNow();
			if(now.compareTo(ZqDateUtil.getDatehms(startTime)) >= 0 && now.compareTo(ZqDateUtil.getDatehms(endTime)) <= 0){
				resp.setLotteryStatus("1");
			}
		}
		//查询是否已经参加过本期抽奖
		YnLotteryRecordEntity record = ynLotteryRecordService.queryLottery(ynuser);
		if(record != null){
			resp.setYesnoLottery("1");
		}
		
		Map<String,Object> map = new HashMap<>();
		map.put("userId", ynuser.getId());
		//查询我的总抽奖次数
		List<YnLotteryRecordDTO> list1 = ynLotteryRecordService.list(map);
		//总中奖金额
		BigDecimal totalAmount = BigDecimal.ZERO;
		for(YnLotteryRecordDTO dto : list1){
			//等级不为空--已开奖
			if(!StringUtils.isBlank(dto.getLotteryLevel())){
				totalAmount = totalAmount.add(dto.getAmount());
			}
		}
		resp.setLotteryTotalNum(list1.size()+"");
		resp.setLotteryTotalAmount(MoneyUtil.bigDecimal2String(totalAmount, 2));
		//查询是否有未读
		map.put("yesnoRead", "0");
		List<YnLotteryRecordDTO> list = ynLotteryRecordService.list(map);
		resp.setYesnoLottery(list.size()+"");
		
		
		log.info("抽奖信息返回:{}",JSON.toJSONString(resp));
		return resp;
	}

	/**
	 * 抽奖
	 */
	@Override
	public void lottery(YnUserEntity ynuser) {
		log.info("抽奖参数:{}",JSON.toJSONString(ynuser));
		String yyyyMMdd = ZqDateUtil.yyyyMMdd(ZqDateUtil.getNow());
		//查询本期抽奖信息
		QueryWrapper<YnLotteryEntity> wrapper = new QueryWrapper<YnLotteryEntity>();
		wrapper.eq(StringUtils.isNotBlank(yyyyMMdd), "sign_no", yyyyMMdd);
		YnLotteryEntity lottery = baseDao.selectOne(wrapper);
		//判断是否在抽奖时间内
		String time = lottery.getLotteryTime();
		String startTime = time.split("#")[0];
		String endTime = time.split("#")[1];
		Date now = ZqDateUtil.getNow();
		//当前时间在抽奖时间段内
		if(now.compareTo(ZqDateUtil.getDatehms(startTime)) < 0){
			throw new RenException(ErrorCode.LOTTERY_TIME_MIN);
		}
		if(now.compareTo(ZqDateUtil.getDatehms(endTime)) > 0){
			throw new RenException(ErrorCode.LOTTERY_TIME_MAX);
		}

		//查询是否参加过挑战
		List<YnSignRecordEntity> list = ynSignRecordService.querySign(ynuser);
		if(list == null){
			throw new RenException(ErrorCode.NOT_SIGN);
		}
		
		//查询是否已经参加过本期抽奖
		YnLotteryRecordEntity record = ynLotteryRecordService.queryLottery(ynuser);
		if(record != null){
			throw new RenException(ErrorCode.SIGN_IS_EXIST);
		}
		
		//添加用户抽奖记录
		YnLotteryRecordEntity entity = new YnLotteryRecordEntity();
		entity.setLotteryId(lottery.getId());
		entity.setUserId(ynuser.getId());
		entity.setSignNo(yyyyMMdd);
		entity.setCreateDate(ZqDateUtil.getNow());
		ynLotteryRecordService.insert(entity);
		//更新抽奖参加人数
		YnLotteryEntity lotteryCount = new YnLotteryEntity();
		lotteryCount.setLotteryCount(lottery.getLotteryCount() + 1);
		lotteryCount.setId(lottery.getId());
		lotteryCount.setUpdateDate(ZqDateUtil.getNow());
		baseDao.updateById(lotteryCount);
	}


}